/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.editura.oxygen.severin.imageviewer.features;

import de.editura.oxygen.severin.imageviewer.features.io.resources.KnownDataModels;
import de.editura.oxygen.severin.imageviewer.features.knownDatamodels.ImageRefField;
import de.editura.oxygen.severin.imageviewer.features.knownDatamodels.ImageRefFieldCntrllr;
import de.editura.oxygen.severin.imageviewer.features.knownDatamodels.KnownDatamodel;
import de.editura.oxygen.severin.imageviewer.features.io.resources.KnownDatamodelUnmarshaller;
import java.util.List;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.Document;
import ro.sync.exml.editor.EditorPageConstants;
import ro.sync.exml.workspace.api.editor.WSEditor;
import ro.sync.exml.workspace.api.editor.page.text.WSTextEditorPage;
import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace;

/**
 *
 * @author kschmidtner
 */
public class TextEditorCaretListener implements CaretListener {

    private StandalonePluginWorkspace pluginWorkspaceAccess = null;
    private ImageViewerPanelController imgVPC = null;
    private List<KnownDatamodel> kdmList = KnownDataModels.getInstance().getKdms();
    boolean firstTime = true;
    KnownDatamodel kdm = null;
    int tries = 100;
    int currentFramingElementOffset = 0;
    ImageReferenceSearch imgRefSearcher = new ImageReferenceSearch();

    public TextEditorCaretListener(StandalonePluginWorkspace pluginWorkspaceAccess, ImageViewerPanelController imgVPC) {
        this.pluginWorkspaceAccess = pluginWorkspaceAccess;
        this.imgVPC = imgVPC;
        this.kdmList = new KnownDatamodelUnmarshaller().unmarshallKnownDatamodels();
    }

    public void caretUpdate(CaretEvent e) {
        WSEditor editorAccess = pluginWorkspaceAccess.getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
        if (editorAccess != null & EditorPageConstants.PAGE_TEXT.equals(editorAccess.getCurrentPageID())) {
            WSTextEditorPage textEditor = (WSTextEditorPage) editorAccess.getCurrentPage();
            int offset = textEditor.getCaretOffset();
            //System.out.println("[TextEditorCaretListener.caretUpdate] Offset: " + offset);
            Document doc = textEditor.getDocument();

            if (firstTime) { // Beim ersten Start wird 100 mal versucht, das Datenformat zu ermitteln.
                if (tries > 0) {
                    initFirstTime(doc, offset);
                }
            }
            if (!firstTime) {
                updateImageViewer(doc, offset);
            }

        }
    }

    /**
     * Find a KnownDatamodel
     * @param doc
     * @param offset
     */
    public void initFirstTime(Document doc, int offset) {

        for (KnownDatamodel knownDatamodel : kdmList) {
            int currentFramePosition = currentFrameElementOffset(doc, offset, knownDatamodel);
            if (currentFramePosition > 0) {
                firstTime = false;
                kdm = knownDatamodel;
//                System.out.println("[TextEditorCaretListener.initFirstTime] KnownDatamodel: " + kdm.getXmlFormat());
//                System.out.println("[TextEditorCaretListener] Versuche: " + versuche);
                break;
            }
        }
        tries--;
    }

    public int currentFrameElementOffset(Document doc, int offset, KnownDatamodel kdm) {
        String searchForOpenTag = imgRefSearcher.getStartOpenTag() + kdm.getCssRootElement();
        return imgRefSearcher.searchBackwardsPosition(doc, offset, searchForOpenTag);
    }

    private void updateImageViewer(Document doc, int offset) {

        String imgPathValue = "";
        ImageRefField imgRefPath = ImageRefFieldCntrllr.getImgDirField(kdm.getImgRefFields());
        ImageRefField imgRefFile = ImageRefFieldCntrllr.getImgFileField(kdm.getImgRefFields());

        int offsetFrameElement = currentFrameElementOffset(doc, offset, kdm);

        if (currentFramingElementOffset != offsetFrameElement) { 
            //Erst wenn sich der Cursor in einen neuen Frame-Element befindet, aktualisiere den Rest
            currentFramingElementOffset = offsetFrameElement;
            if (imgRefPath != null) {
                imgPathValue = imgRefSearcher.searchForImgValue(doc, offsetFrameElement, imgRefPath) + "/";
            }
            String imgFileValue = imgRefSearcher.searchForImgValue(doc, offsetFrameElement, imgRefFile);

            if (imgFileValue != null) {
                String imgRef = imgPathValue + imgFileValue;
                //System.out.println("ImgRef: " + imgRef);
                imgVPC.refreshImageViewer(imgRef);
            }
        }
    }
}
